package com.pay.cloud.fragment;

import com.pay.cloud.BindState;
import com.pay.cloud.DataFactory;
import com.pay.cloud.StatusListener;
import com.pay.cloud.cpay.MyCloudPay;
import com.pay.cloud.cpay.QueryShopInfoRequest;
import com.pay.cloud.cpay.QueryShopInfoResponse;
import com.pay.cloud.cpay.ShopInfo;
import com.pay.cloud.cpay.StaffInfo;

import java.util.List;

import static com.pay.cloud.fragment.TipFragment.TipType.WAIT;

public class ShopShiftFragment extends TipVerticalFragment implements BindState {
    private StatusListener listener;
    private String staffId;
    public ShopShiftFragment(String staffId, StatusListener listener) {
        super(WAIT, "正在切换店员");
        this.staffId = staffId;
        this.listener = listener;
    }

    @Override
    public boolean useNetwork() {
        return true;
    }

    @Override
    public void execute() throws Exception {
        StaffInfo staff = queryStaff();
        DataFactory.getDataStore().setStaffId(staffId);
        DataFactory.getDataStore().setStaffName(staff.getStaff_name());
        onSuccess(staff.getStaff_name());
    }

    @Override
    public void onError(String msg) {
        listener.onError(msg);
        speak("店员切换失败");
    }

    private void onSuccess(String staffName) {
        listener.onSuccess("切换店员：" + staffName);
        speak("店员切换成功");
    }

    private StaffInfo queryStaff() throws Exception {
        String outShopId = DataFactory.getDataStore().getOutShopId();
        if (null == outShopId) {
            throw new Exception("门店信息不存在");
        }
        QueryShopInfoRequest req = new QueryShopInfoRequest();
        req.setPage_num(1);
        req.setPage_size(100);
        QueryShopInfoResponse res = MyCloudPay.getInstance(getActivity()).queryShopInfo(req);
        if (res.getTotal_count() == 0) {
            throw new Exception("门店信息不存在");
        }
        List<ShopInfo> shops = res.getShop_infos();
        ShopInfo shop = null;
        for (ShopInfo item: shops) {
            if (item.getOut_shop_id().equals(outShopId)) {
                shop = item;
                break;
            }
        }
        if (null == shop) {
            throw new Exception("门店信息不存在");
        }
        List<StaffInfo> staffs = shop.getStaff_infos();
        StaffInfo staff = null;
        for (StaffInfo item: staffs) {
            if (item.getStaff_id().equals(staffId)) {
                staff = item;
                break;
            }
        }
        if (null == staff) {
            throw new Exception("店员不存在");
        }
        return staff;
    }

}
